package com.lysj.lyd_pay.wx.feignImpl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.XmlUtil;
import com.jpay.ext.kit.PaymentKit;
import com.jpay.weixin.api.WxPayApi;
import com.lysj.admin.common.pay.domain.PayParam;
import com.lysj.admin.common.pay.domain.RefundParam;
import com.lysj.admin.common.pay.feign.WxPayServiceFeign;
import com.lysj.admin.utils.exception.BaseException;
import com.lysj.admin.utils.web.ParamUtil;
import lombok.extern.slf4j.Slf4j;
import me.hao0.wepay.core.Wepay;
import me.hao0.wepay.core.WepayBuilder;
import me.hao0.wepay.model.pay.JsPayRequest;
import me.hao0.wepay.model.pay.JsPayResponse;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 15:01 2019/3/21
 * @ Description:
 **/
@RestController
@Slf4j
public class WxPayServiceFeignImpl implements WxPayServiceFeign {

    @Value("${wxpayconfig.notifyUrl}")
    private String notifyUrl;

    @Value("${wxpayconfig.clientIp}")
    private String clientIp;

    @Override
    public Map<String, Object> createOrder(@RequestBody PayParam payParam) {
        log.info("进入支付");
        //组装微信支付实体
        Wepay wepay = WepayBuilder
                .newBuilder("wx7a42f66de632b299", "AD440BD8EB4C4C17B4AC9B49E573381A", "1503880611").build();
        JsPayRequest jsPayRequest = new JsPayRequest();
        jsPayRequest.setBody("微信支付");
        jsPayRequest.setOpenId(payParam.getOpenid());
        jsPayRequest.setNotifyUrl(notifyUrl);
        jsPayRequest.setTotalFee(payParam.getTolPrice());
        jsPayRequest.setOutTradeNo(payParam.getOutTradeNo());
        jsPayRequest.setClientIp(clientIp);
        jsPayRequest.setTimeStart(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        log.info("订单号{}"+payParam.getOutTradeNo());
        JsPayResponse jsPayResponse = null;
        Map<String, Object> map = new HashMap<>();
        map.put("jsPayResponse", "");
        try {
            jsPayResponse = wepay.pay().jsPay(jsPayRequest);
        } catch (Exception e) {
            e.printStackTrace();
            return map;
        }
        map.put("jsPayResponse", jsPayResponse);
        return map;
    }


    /**
     * 退款
     */
    @Override
    public boolean refund(@RequestBody RefundParam refundParam) {
        // 获取微信退款证书文件
        File file = null;
        try {
            file = (ResourceUtils.getFile("classpath:config/apiclient_cert.p12"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
        String certPath = file.getAbsolutePath();
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", refundParam.getAppId());
        params.put("mch_id", refundParam.getMchId());
        params.put("nonce_str", System.currentTimeMillis() + "");
        params.put("out_trade_no", refundParam.getOutTradeNo());
        params.put("out_refund_no", System.currentTimeMillis() + "");
        params.put("total_fee", String.valueOf(refundParam.getTotalFee()));
        params.put("refund_fee",String.valueOf(refundParam.getReturnFee()));
        params.put("sign", PaymentKit.createSign(params, refundParam.getAppSecrect()));
        String refund = "";
        try {
            refund = WxPayApi.orderRefund(false, params, certPath, refundParam.getMchId());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        //解析返回的xml信息
        Map<String, String> map = new HashMap<String, String>();
        Document docment = null;
        try {
            docment = DocumentHelper.parseText(refund);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        Element root = docment.getRootElement();
        List<Element> list = root.elements();
        for (Element ele : list) {
            map.put(ele.getName(), ele.getText());
        }
        //若退款成功
        if ("SUCCESS".equals(map.get("return_code"))) {
            return true;
        }
        return false;
    }


}
